package nthu.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public abstract class ResourceController<R> extends HttpServlet {
	public static final String MODEL_ATTRIBUTE_NAME = "model";
	
	public void setModel(HttpServletRequest request, R resource) {
		request.setAttribute(MODEL_ATTRIBUTE_NAME, resource);
	}

	@SuppressWarnings("unchecked")
	public R getModel(HttpServletRequest request) {
		return (R) request.getAttribute(MODEL_ATTRIBUTE_NAME);
	}

	public String getRequestBody(HttpServletRequest request) throws IOException {
		StringBuffer buf = new StringBuffer();
		char[] c = new char[1024];
		int len;
		while((len = request.getReader().read(c)) != -1) {
			buf.append(c, 0, len);
		}
		return buf.toString();
	}

	public void forward(HttpServletRequest request, HttpServletResponse response, String path)
			throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(path);
		if(dispatcher == null)
			throw new IllegalArgumentException();
		dispatcher.forward(request, response);
	}

	public void include(HttpServletRequest request, HttpServletResponse response, String path)
			throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(path);
		if(dispatcher == null)
			throw new IllegalArgumentException();
		dispatcher.include(request, response);
	}	
}

